<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="年级" prop="grade">
        <el-select v-model="queryParams.grade" clearable filterable placeholder="请选择年级" @change="getFormclassList">
          <el-option v-for="dict in dict.type.year_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" clearable filterable placeholder="请选择班级">
          <el-option v-for="item in classList" :key="item.id" :label="item.label" :value="item.id" size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="测量结果" prop="visionResult">
        <el-select v-model="queryParams.visionResult" placeholder="请选择测量结果" clearable size="small">
          <el-option v-for="dict in dict.type.vision_result" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-circle-close" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="设备名称" align="center" prop="year" />-->
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="姓名" align="center" prop="stuName" />
      <el-table-column label="左眼视力" align="center" prop="leftEyeVision" />
      <el-table-column label="右眼视力" align="center" prop="rightEyeVision" />
      <el-table-column label="测量结果" align="center" prop="visionResult">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.vision_result" :value="scope.row.visionResult" />
        </template>
      </el-table-column>
      <el-table-column label="测量时间" align="center" prop="visionTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.readTime == null" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-if="scope.row.readTime == null" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工作汇报对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" clearable filterable placeholder="请选择年级" @change="getclassList">
            <el-option v-for="dict in dict.type.year_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" clearable filterable placeholder="请选择班级" @change="getStuList">
            <el-option v-for="item in classList" :key="item.id" :label="item.label" :value="item.id" size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="幼儿姓名" prop="stuId">
          <el-select v-model="form.stuId" clearable filterable placeholder="请选择幼儿姓名">
            <el-option v-for="item in stuList" :key="item.id" :label="item.name" :value="item.id" size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测量结果" prop="visionResult">
          <el-radio-group v-model="form.visionResult">
            <el-radio v-for="dict in dict.type.vision_result" :label="parseInt(dict.value)" :key="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="左眼视力" prop="leftEyeVision">
          <el-input v-model="form.leftEyeVision" type="number" placeholder="请输入左眼视力" step="0.1" min="0" max="2.0" />
        </el-form-item>
        <el-form-item label="右眼视力" prop="rightEyeVision">
          <el-input v-model="form.rightEyeVision" type="number" placeholder="请输入右眼视力" step="0.1" min="0" max="2.0" />
        </el-form-item>
        <el-form-item label="测量时间" prop="visionTime">
          <el-date-picker clearable size="small" v-model="form.visionTime" type="date" :picker-options="pickerOptions"
            value-format="yyyy-MM-dd" placeholder="选择测量时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


import { selectClazz } from "@/api/base/clazz";
import { addstuVision, delstuVision, stuVision, updatestuVision } from "@/api/base/ill";
import { addStudent, delStudent, listStudent, updateStudent } from "@/api/base/student";

export default {
  name: "gzt",
  dicts: ['vision_result', 'year_type'],
  data() {
    const leftEye = (rule, value, callback) => {
      if (value > 2) {
        callback(new Error("左眼度数最高为2.0"));
      } else {
        callback();
      }
    };
    const rightEye = (rule, value, callback) => {
      if (value > 2) {
        callback(new Error("右度数最高为2.0"));
      } else {
        callback();
      }
    };
    return {
      title: '',
      open: false,
      form: {},
      rules: {
        grade: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        stuId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        visionResult: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        leftEyeVision: [
          { required: true, message: "不能为空", trigger: "blur" },
          { required: true, validator: leftEye, trigger: "blur" }

        ],
        rightEyeVision: [
          { required: true, message: "不能为空", trigger: "blur" },
          { required: true, validator: rightEye, trigger: "blur" }

        ],
      },
      // 总条数
      total: 0,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schoolCode: this.$store.getters.schoolCode,
      },
      classList: [],
      reportList: [],
      stuList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  created() {

    /**列表接口**/
    this.getList()
  },
  methods: {
    /** 查询视力列表 */
    async getList() {
      try {
        this.loading = true;
        const data = await stuVision(this.queryParams)
        this.reportList = data.rows;
        this.total = data.total;
        this.loading = false;

      } catch (e) {
        console.log(e)
      }
    },
    /** 查询条件班级列表 */
    async getFormclassList() {
      try {
        let params = {}
        this.$set(this.queryParams, 'classId', '')
        if (this.queryParams.grade) params.year = this.queryParams.grade;
        const { rows } = await selectClazz(params);
        this.classList = rows.map(item => {
          return {
            id: item.id,
            label: item.title,
          }
        })
      } catch (e) {
        console.log(e)
      }
    },
    /** 查询班级列表 */
    async getclassList() {
      try {
        let params = {}
        this.$set(this.form, 'classId', '')
        this.$set(this.form, 'stuId', '')
        if (this.form.grade) params.year = this.form.grade;
        const { rows } = await selectClazz(params);
        this.classList = rows.map(item => {
          return {
            id: item.id,
            label: item.title,
          }
        })
      } catch (e) {
        console.log(e)
      }
    },
    /**查询学生**/
    async getStuList() {
      try {
        let params = {}
        this.$set(this.form, 'stuId', '')
        if (this.form.classId) params.classId = this.form.classId;
        const data = await listStudent(params)
        this.stuList = data.rows;
      } catch (e) {
        console.log(e)
      }
    },
    /**提交*/
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //重新组装设备信息

          if (this.form.id != null) {
            updatestuVision(this.form).then(response => {
              if (response.code == 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addstuVision(this.form).then(response => {
              if (response.code == 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.form = JSON.parse(JSON.stringify(row));
      /**班级**/
      this.getclassList()
      /**学生接口**/
      this.getStuList()
      this.open = true;
      this.title = "修改学生视力信息";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生视力信息";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      // this.$confirm('是否确认删除学生编号为"' + ids + '"的数据项?', "警告", {
        this.$confirm('是否确认删除选中的学生数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delstuVision(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuId: null,
        leftEyeVision: null,
        rightEyeVision: null,
        visionResult: null,
        classId: null,
        schoolCode: this.$store.getters.schoolCode,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  }
};
</script>
